package com.power.ding.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import com.alibaba.fastjson.JSONObject;
import com.plf.common.utils.RestUtil;
import com.plf.common.utils.RestUtil.HttpClient;
import com.plf.common.utils.RestUtil.HttpResponse;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.digest.DigestUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 快递查询
 * 调用快递鸟API
 * https://www.yuque.com/kdnjishuzhichi/dfcrg1/hl2gthcuqft7rm34
 * @author wangn
 */
@Slf4j
public class ExpressUtil {
	private String userid="1834940";
	private String apikey="e95b6baa-5f00-4d99-be0e-fa8a9757c611";
//	private String shipper="STO";
	
	private static String URL_QUERY="https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx";
	private static String TYPE_QUERY="8001";
	
	/**
	 * 查询快递运输轨迹
	 * @param code：快递单号
	 * @param shipper：快递公司编码
	 * @param desc：是否降序排列
	 * @throws Exception
	 */
	public void query(String code, String shipper, Boolean desc) throws Exception {
		JSONObject data=new JSONObject();
		data.put("ShipperCode", shipper);
		data.put("LogisticCode", code);
		if(desc) {
			data.put("Sort", 1); //降序
		}
		
		String requestData=data.toString();
		log.info("requestData: {}", requestData);
		String dataSign=signData(requestData);
		log.info("dataSign: {}", dataSign);
		
		HttpClient client = RestUtil.getClient(URL_QUERY)
				.addPostParam("RequestData", requestData)
				.addPostParam("RequestType", TYPE_QUERY)
				.addPostParam("EBusinessID", userid)
				.addPostParam("DataSign", dataSign)
				.addPostParam("DataType", "2")
				.post();
		HttpResponse resp = client.request();
		JSONObject back = (JSONObject) resp.getContent();
		log.info("back: {}", back);
	}

	/**
	 * 请求体签名
	 * @param requestData
	 * @return
	 * @throws UnsupportedEncodingException 
	 */
	private String signData(String requestData) throws UnsupportedEncodingException {
		String dataSign=requestData+apikey;
		log.info("dataSign + apikey: {}", dataSign);
		dataSign=DigestUtil.md5Hex(dataSign);
		log.info("md5: {}", dataSign);
		dataSign=Base64.encode(dataSign);
		log.info("base64: {}", dataSign);
		dataSign=URLEncoder.encode(dataSign, "UTF-8");
		log.info("url: {}", dataSign);
		return dataSign;
	}
	
	public static void main(String[] aaa) {
		ExpressUtil ep=new ExpressUtil();
		try {
			ep.query("773270960450177", "STO", true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
